// pages/doodle/doodle.js
const music = wx.createInnerAudioContext()
let ctx;
Page({

  /**
   * 页面的初始数据
   */
  data: {
    paused:false,
    pen:{
      lineWidth:5,
      color:"#cc0033"
    },
    canvasWidth:0,
    canvasHeight:0
  },

  touchstart:function(e) {
    ctx.setStrokeStyle(this.data.pen.color);
    ctx.setLineWidth(this.data.pen.lineWidth);
    ctx.moveTo(e.touches[0].x, e.touches[0].y);
  },
  touchmove:function(e) {
    let x = e.touches[0].x;
    let y = e.touches[0].y;
    ctx.lineTo(x, y)
    ctx.stroke();
    ctx.draw(true);
    ctx.moveTo(x,y)
  },
  penselect:function(e) {
    console.log(e)
    this.setData({'pen.lineWidth':e.currentTarget.dataset.param})
  },
  colorselect:function(e) {
    this.setData({ 'pen.color': e.currentTarget.dataset.param })
  },
  clearCanvas:function(){
    var width = this.data.canvasWidth
    var height = this.data.canvasHeight
    wx.showModal({
      title:'清空涂鸦',
      content:'确定要清空所有的涂鸦吗？',
      success:function(res){
        if(res.confirm){
          ctx.clearRect(0,0,width,height)
          ctx.draw()
        }
      }
    })
  },
  musicstat:function(){
    var paused = false
    if(music.paused){
      music.play()
      paused = false
    }else{
      music.pause()
      paused = true
    }
    this.setData({
      paused:paused
    })
  },
  down:function(){
    wx.canvasToTempFilePath({
      canvasId:'myCanvas',
      success:function(res){
        console.log(res)
        wx.saveImageToPhotosAlbum({
          filePath: res.tempFilePath,
          success:function(res){
            wx.showToast({
              title: '已保存至相册',
            })
          }
        })
      }
    })
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    var that = this

    ctx=wx.createCanvasContext('myCanvas');
    ctx.setStrokeStyle(this.data.pen.color);
    ctx.setLineWidth(this.data.pen.lineWidth);
    ctx.setLineCap('round');
    ctx.setLineJoin('round');

    music.src = "/audios/bg.mp3"
    music.autoplay = true
    music.loop = true
    music.onCanplay(function(){
      music.play()
    })

    /*
    wx.createSelectorQuery().select('.myCanvas').boundingClientRect().exec(function(res){
      console.log(res)
      that.setData({
        canvasWidth: res[0].width,
        canvasHeight: res[0].height
      });
    })
    */
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    music.onCanplay(function(){
      music.play()
    })
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
    music.pause()
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    music.pause()
  },
})